#!/usr/X11R6/bin/python3.1
import os
import cgi
import cgitb
from http.cookies import SimpleCookie
from pygallib import userlib
from pygallib import usersession
from pygallib.usersession import LoginError
from pygallib import layoutlib

cgitb.enable()

sid = -1
login_success = False
login_attempt = False
fields = cgi.FieldStorage()
if "username" in fields:
  # Try to login
  try:
    login_attempt = True
    sid = usersession.login(fields["username"].value, fields["password"].value)
    login_success = True
  except LoginError:
    pass

headers = {}
headers["Content-type"] = "text/html"
if login_success:
  headers["Set-Cookie"] = "pygallery_sid=%s" % sid
layoutlib.print_http_headers(headers)
layoutlib.print_page_open("PyGallery - Login")
print("<body>")

menu = []
menu.append(("Home", "gallery.cgi"))
layoutlib.print_page_menu(menu)

if usersession.logged_in():
  print('You are already logged in, click ' + 
      '<a href="gallery.cgi">here</a> for the gallery.') 
else:
  # Print login form
  if login_attempt:
    if login_success:
      print('<p>Login success, click ' + 
        '<a href="gallery.cgi">here</a> for the gallery.') 
    else:
      print('<p>Login failed.</p>')
  print("""
  <form action="login.cgi" method="post">
    Username: <input type="text" name="username" />
    Password: <input type="password" name="password" />
    <input type="submit" value="Login" />
  </form>
  """)
layoutlib.print_page_close()
